package MyApp;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.R;

import java.util.List;

public class MemoAdapter extends RecyclerView.Adapter<MemoAdapter.MemoViewHolder> {

    private List<Memo> memoList;
    private OnDeleteClickListener onDeleteClickListener; // 删除点击事件监听器

    public interface OnDeleteClickListener {
        void onDeleteClick(int position);
    }

    public MemoAdapter(List<Memo> memoList, OnDeleteClickListener listener) {
        this.memoList = memoList;
        this.onDeleteClickListener = listener;
    }

    @NonNull
    @Override
    public MemoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.memo_item, parent, false);
        return new MemoViewHolder(itemView, onDeleteClickListener);
    }

    @Override
    public void onBindViewHolder(@NonNull MemoViewHolder holder, int position) {
        Memo memo = memoList.get(position);
        holder.bind(memo);
    }

    @Override
    public int getItemCount() {
        return memoList.size();
    }

    public static class MemoViewHolder extends RecyclerView.ViewHolder {
        Button deleteButton;
        TextView memoContent;
        TextView memoTimestamp;

        public MemoViewHolder(View itemView, final OnDeleteClickListener listener) {
            super(itemView);
            deleteButton = itemView.findViewById(R.id.deleteButton);
            memoContent = itemView.findViewById(R.id.memoContent);
            memoTimestamp = itemView.findViewById(R.id.memoTimestamp);
            deleteButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.onDeleteClick(getAdapterPosition());
                    }
                }
            });
        }

        public void bind(Memo memo) {
            // 绑定数据到视图元素
            memoContent.setText(memo.getContent());
            memoTimestamp.setText(memo.getTimestamp());
        }
    }
}